package cn.cxion.chat.app.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lqr.optionitemview.OptionItemView;
import com.zhy.android.percent.support.PercentLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cxion.chat.R;
import cn.cxion.chat.app.bean.CheckContractBean;
import cn.cxion.chat.app.bean.CheckContractDetail;
import cn.cxion.chat.app.bean.CheckProcessDetail;
import cn.cxion.chat.app.bean.MessageAction;
import cn.cxion.chat.app.bean.MessageEvent;
import cn.cxion.chat.app.bean.OnHandInfo;
import cn.cxion.chat.app.constant.Constant;
import cn.cxion.chat.app.util.CheckUtil;
import cn.cxion.chat.app.util.IflyUtil;
import cn.cxion.chat.app.util.LogUtil;
import cn.cxion.chat.app.util.StringUtil;
import cn.cxion.chat.app.util.UiHelp;
import cn.cxion.chat.kit.utils.FileUtils;

public class CheckContractView {

    private View view;
    private Activity activity;
    private int classType;
    private ViewHolder holder;
    private String path;
    private String fileNmae;
    private CheckContractBean checkContractBean;

    public CheckContractView(Context context, int classType) {
        view = LayoutInflater.from(context).inflate(R.layout.view_checkcontract, null);
        activity = (Activity) context;
        this.classType = classType;
        init();
    }

    public CheckContractView(Context context, int classType, CheckContractBean checkContractBean) {
        view = LayoutInflater.from(context).inflate(R.layout.view_checkcontract, null);
        activity = (Activity) context;
        this.classType = classType;
        this.checkContractBean = checkContractBean;
        init();
    }

    public View getView() {
        return view;
    }

    private void init() {
        EventBus.getDefault().register(this);
        holder = new ViewHolder(activity, view);
        viewControl();
        holder.accessory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtil.isEmpty(path))
                    activity.startActivity(FileUtils.getViewIntent(activity, new File(path)));
            }
        });
        if (checkContractBean != null && (classType == Constant.CLAIM || classType == Constant.CLAIMDETAIL || classType == Constant.DEMANDDETAILS)) {
            CheckContractDetail detail = checkContractBean.getDemandDetail();
            path = detail.getAccessoryPath();
            //预防空值报错
            UiHelp.getInstance().setText(detail.getAccessoryName(), holder.accessory)
                    .setText(detail.getContent(), holder.etSuggest);
            holder.swichtEigency.setChecked(detail.isExigency());
            holder.etSuggest.setEnabled(false);
            holder.setClickAble(false);
            holder.swichtEigency.setEnabled(false);
            holder.imgRecognize.setVisibility(View.GONE);
        } else if (checkContractBean != null && checkContractBean.getCheckContractDeatail() != null && classType == Constant.CONTRACTDETAILS) {
            CheckContractDetail detail = checkContractBean.getCheckContractDeatail();
            path = detail.getAccessoryPath();
            //预防空值报错
            UiHelp.getInstance().setText(detail.getAccessoryName(), holder.accessory)
                    .setText(detail.getContent(), holder.etSuggest);
            holder.swichtEigency.setChecked(detail.isExigency());
            holder.etSuggest.setEnabled(false);
            holder.setClickAble(false);
            holder.swichtEigency.setEnabled(false);
            holder.imgRecognize.setVisibility(View.GONE);
        } else if (checkContractBean != null && checkContractBean.getApproveDetail() != null && classType == Constant.APPROVE) {
            CheckContractDetail detail = checkContractBean.getApproveDetail();
            path = detail.getAccessoryPath();
            //预防空值报错
            UiHelp.getInstance().setText(detail.getAccessoryName(), holder.accessory)
                    .setText(detail.getContent(), holder.etSuggest);
            holder.swichtEigency.setChecked(detail.isExigency());
            holder.etSuggest.setEnabled(false);
            holder.setClickAble(false);
            holder.swichtEigency.setEnabled(false);
            holder.imgRecognize.setVisibility(View.GONE);
        }else if (checkContractBean != null && checkContractBean.getCustomerApproveDetail() != null && classType == Constant.CUSTOMERAPPROVE) {
            CheckContractDetail detail = checkContractBean.getCustomerApproveDetail();
            path = detail.getAccessoryPath();
            //预防空值报错
            UiHelp.getInstance().setText(detail.getAccessoryName(), holder.accessory)
                    .setText(detail.getContent(), holder.etSuggest);
            holder.swichtEigency.setChecked(detail.isExigency());
            holder.etSuggest.setEnabled(false);
            holder.setClickAble(false);
            holder.swichtEigency.setEnabled(false);
            holder.imgRecognize.setVisibility(View.GONE);
        } else {
            holder.setClickAble(true);
            holder.imgRecognize.setVisibility(View.VISIBLE);
        }
    }

    //保存按钮
    public void rightClick() {
        if (classType == Constant.DEMANDDETAILS || classType == Constant.CONTRACTCREATIONVIEW) {
            save();
        } else if (classType == Constant.CONTRACTDETAILS) {
            saveContract();
        } else if (classType == Constant.APPROVE) {
            saveApprove();
        }  else if (classType == Constant.CUSTOMERAPPROVE) {
            saveCustomerApprove();
        } else if (classType == Constant.CLAIM) {
            MaterialDialog dialog = new MaterialDialog.Builder(activity)
                    .content("是否认领")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            ToastUtils.showShort("认领成功！");
                            cliam();
                        }
                    }).build();
            dialog.show();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(MessageEvent messageEvent) {
        if (messageEvent.getKey() == MessageAction.SendFileName) {
            fileNmae = messageEvent.getMessage();
            if (fileNmae.length() > 15) {
                fileNmae = fileNmae.substring(0, 15) + "...";
            }
            holder.accessory.setTitleText(fileNmae);
        }
        if (messageEvent.getKey() == MessageAction.SendFilePath) {
            path = messageEvent.getMessage();
        }
        if (messageEvent.getKey() == MessageAction.CheckContractUnregister) {
            unregister();
        }
    }

    private void cliam() {
        getBean();
        List<CheckProcessDetail> list = checkContractBean.getCheckProcessDetailList();
        CheckProcessDetail checkProcessDetail = new CheckProcessDetail();
        checkProcessDetail.setState(Constant.waitDispose);
        checkProcessDetail.setStateName("认领");
        checkProcessDetail.setTitle("律师认领");
        checkProcessDetail.setOperator("大熊（已认领）");
        checkProcessDetail.setRemark("预计10.15完成合同审改");
        checkProcessDetail.setTime(StringUtil.getDay());
        checkProcessDetail.setTimestamp(SystemClock.elapsedRealtime());
        list.add(checkProcessDetail);
        checkContractBean.setCheckProcessDetailList(list);
        checkContractBean.getOnHandInfo().setState(Constant.onHand);
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshOnhand, ""));
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshCliam, ""));
        activity.finish();
    }

    private void saveContract() {
        if (!CheckUtil.checkEditText(activity, "审批意见不能为空！", holder.etSuggest))
            return;
        getBean();
        //保存审改内容
        CheckContractDetail deatail = new CheckContractDetail();
        deatail.setContent(holder.etSuggest.getText().toString());
        deatail.setAccessoryName(fileNmae);
        deatail.setAccessoryPath(path);
        deatail.setExigency(holder.swichtEigency.isChecked());
        checkContractBean.setCheckContractDeatail(deatail);

        List<CheckProcessDetail> list = checkContractBean.getCheckProcessDetailList();
        CheckProcessDetail checkProcessDetail = new CheckProcessDetail();
        checkProcessDetail.setState(Constant.waitDispose);
        checkProcessDetail.setStateName("审改");
        checkProcessDetail.setTitle("审改完毕");
        checkProcessDetail.setOperator("附件XXX");
        checkProcessDetail.setRemark("预计10.15完成合同审改");
        checkProcessDetail.setTime(StringUtil.getDay());
        checkProcessDetail.setTimestamp(SystemClock.elapsedRealtime());
        list.add(checkProcessDetail);
        checkContractBean.setCheckProcessDetailList(list);
        checkContractBean.getOnHandInfo().setState(Constant.onHand);
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshOnhand, ""));
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshCliam, ""));
        activity.finish();
    }

    private void saveApprove() {
        if (!CheckUtil.checkEditText(activity, "审批意见不能为空！", holder.etSuggest))
            return;
        getBean();
        //保存审改内容
        CheckContractDetail deatail = new CheckContractDetail();
        deatail.setContent(holder.etSuggest.getText().toString());
        deatail.setAccessoryName(fileNmae);
        deatail.setAccessoryPath(path);
        deatail.setExigency(holder.swichtEigency.isChecked());
        checkContractBean.setApproveDetail(deatail);
        List<CheckProcessDetail> list = checkContractBean.getCheckProcessDetailList();
        CheckProcessDetail checkProcessDetail = new CheckProcessDetail();
        checkProcessDetail.setState(Constant.waitDispose);
        checkProcessDetail.setStateName("审批");
        checkProcessDetail.setTitle("团队内部审批");
        checkProcessDetail.setOperator(holder.etSuggest.getText().toString());
        checkProcessDetail.setRemark("预计10.15完成合同审改");
        checkProcessDetail.setTime(StringUtil.getDay());
        checkProcessDetail.setTimestamp(SystemClock.elapsedRealtime());
        list.add(checkProcessDetail);
        checkContractBean.setCheckProcessDetailList(list);
        checkContractBean.getOnHandInfo().setState(Constant.onHand);
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshOnhand, ""));
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshCliam, ""));
        activity.finish();
    }

    private void saveCustomerApprove() {
        if (!CheckUtil.checkEditText(activity, "详情不能为空！", holder.etSuggest))
            return;
        getBean();
        //保存审改内容
        CheckContractDetail deatail = new CheckContractDetail();
        deatail.setContent(holder.etSuggest.getText().toString());
        deatail.setAccessoryName(fileNmae);
        deatail.setAccessoryPath(path);
        deatail.setExigency(holder.swichtEigency.isChecked());
        checkContractBean.setCustomerApproveDetail(deatail);
        List<CheckProcessDetail> list = checkContractBean.getCheckProcessDetailList();
        CheckProcessDetail checkProcessDetail = new CheckProcessDetail();
        checkProcessDetail.setState(Constant.waitDispose);
        checkProcessDetail.setStateName("完成");
        checkProcessDetail.setTitle("客户确认");
        checkProcessDetail.setOperator(getText());
        checkProcessDetail.setRemark("预计10.15完成合同审改");
        checkProcessDetail.setTime(StringUtil.getDay());
        checkProcessDetail.setTimestamp(SystemClock.elapsedRealtime());
        list.add(checkProcessDetail);
        checkContractBean.setCheckProcessDetailList(list);
        checkContractBean.getOnHandInfo().setState(Constant.onHand);
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshOnhand, ""));
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshCliam, ""));
        activity.finish();
    }

    public void getBean() {
        for (CheckContractBean bean : Constant.getContractBeanList()) {
            if (bean.getUuid().equals(checkContractBean.getUuid())) {
                checkContractBean = bean;
            }
        }
    }

    public String getText() {
        if (holder.statusStocks.isChecked())
            return holder.statusStocks.getText().toString();
        if (holder.statusInhand.isChecked())
            return holder.statusInhand.getText().toString();
        if (holder.statusUntreade.isChecked())
            return holder.statusUntreade.getText().toString();
        return "";
    }

    private void save() {
        if (!CheckUtil.checkEditText(activity, "详情不能为空！", holder.etSuggest))
            return;
        checkContractBean = new CheckContractBean();
        OnHandInfo onHandInfo = new OnHandInfo();
        onHandInfo.setState(Constant.waitDispose);
        onHandInfo.setT1("大熊");
        onHandInfo.setT2("合同审改");
        onHandInfo.setT3(holder.etSuggest.getText().toString());
        onHandInfo.setTime(StringUtil.getDay());
        checkContractBean.setOnHandInfo(onHandInfo);
        CheckContractDetail deatail = new CheckContractDetail();
        deatail.setContent(holder.etSuggest.getText().toString());
        deatail.setAccessoryName(fileNmae);
        deatail.setAccessoryPath(path);
        deatail.setExigency(holder.swichtEigency.isChecked());
        checkContractBean.setDemandDetail(deatail);
        List<CheckProcessDetail> list = new ArrayList<>();
        CheckProcessDetail checkProcessDetail = new CheckProcessDetail();
        checkProcessDetail.setState(Constant.waitDispose);
        checkProcessDetail.setStateName("发起");
        checkProcessDetail.setTitle("发起需求");
        checkProcessDetail.setOperator("海翼集团-大熊");
        checkProcessDetail.setTime(StringUtil.getDay());
        checkProcessDetail.setTimestamp(SystemClock.elapsedRealtime());
        list.add(checkProcessDetail);
        checkContractBean.setCheckProcessDetailList(list);
        checkContractBean.setUuid(StringUtil.getUUID());
        //保存
        Constant.getContractBeanList().add(checkContractBean);
        EventBus.getDefault().post(new MessageEvent(MessageAction.RefreshOnhand, ""));
        MaterialDialog dialog2 = new MaterialDialog.Builder(activity)
                .content("发送中...")
                .progress(true, 100)
                .cancelable(false)
                .build();
        dialog2.show();
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                dialog2.dismiss();
                unregister();
                ToastUtils.showShort("发送成功！");
                activity.finish();
            }
        };
        timer.schedule(timerTask, 500);
    }


    public void unregister() {
        EventBus.getDefault().unregister(this);
    }


    private void viewControl() {
        holder.llCheckcontract.setVisibility(View.VISIBLE);
        holder.llSchedule.setVisibility(View.GONE);
        switch (classType) {
            case Constant.CONTRACTDETAILS:
            case Constant.APPROVE:
                holder.llExigency.setVisibility(View.VISIBLE);
                holder.copyto.setVisibility(View.VISIBLE);
                break;
            case Constant.CUSTOMERAPPROVE:
                holder.llExigency.setVisibility(View.VISIBLE);
                holder.copyto.setVisibility(View.VISIBLE);
                holder.showstatus.setVisibility(View.VISIBLE);
                holder.showstatus.setLeftText("需求确认");
                holder.rgStatus.setVisibility(View.VISIBLE);
                holder.statusStocks.setText("确认需求");
                holder.statusInhand.setText("退回修改");
                holder.statusUntreade.setText("再次发起");
                break;
            case Constant.CONTRACTCREATIONVIEW:
            case Constant.DEMANDDETAILS:
            case Constant.CLAIM:
            case Constant.CLAIMDETAIL:
                holder.llExigency.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    static class ViewHolder {

        @Bind(R.id.et_suggest)
        AutoCompleteTextView etSuggest;
        @Bind(R.id.img_recognize)
        ImageView imgRecognize;
        @Bind(R.id.accessory)
        OptionItemView accessory;
        @Bind(R.id.ll_accessory)
        RelativeLayout llAccessory;
        @Bind(R.id.img_accessory)
        ImageView imgAccessory;
        @Bind(R.id.recipients)
        OptionItemView recipients;
        @Bind(R.id.copyto)
        OptionItemView copyto;
        @Bind(R.id.exigency)
        OptionItemView exigency;
        @Bind(R.id.swith_exigency)
        Switch swichtEigency;
        @Bind(R.id.ll_exigency)
        LinearLayout llExigency;
        @Bind(R.id.ll_accessory_new)
        RelativeLayout llAccessoryNew;
        @Bind(R.id.history)
        OptionItemView history;
        @Bind(R.id.showstatus)
        OptionItemView showstatus;
        @Bind(R.id.status_stocks)
        RadioButton statusStocks;
        @Bind(R.id.status_inhand)
        RadioButton statusInhand;
        @Bind(R.id.status_untreade)
        RadioButton statusUntreade;
        @Bind(R.id.rg_status)
        RadioGroup rgStatus;
        @Bind(R.id.ll_checkcontract)
        PercentLinearLayout llCheckcontract;
        @Bind(R.id.switch_wholeday)
        Switch switchWholeday;
        @Bind(R.id.ll_wholeday)
        LinearLayout llWholeday;
        @Bind(R.id.begin)
        OptionItemView begin;
        @Bind(R.id.finish)
        OptionItemView finish;
        @Bind(R.id.repeat)
        OptionItemView repeat;
        @Bind(R.id.tag)
        OptionItemView tag;
        @Bind(R.id.invitee)
        OptionItemView invitee;
        @Bind(R.id.ll_schedule)
        PercentLinearLayout llSchedule;
        @Bind(R.id.appointmentlawyer)
        OptionItemView appointmentlawyer;
        @Bind(R.id.appointmenttime)
        OptionItemView appointmenttime;
        @Bind(R.id.place)
        OptionItemView place;
        @Bind(R.id.ll_appointmentlawyer)
        PercentLinearLayout llAppointmentlawyer;
        Context context;

        ViewHolder(Context context, View view) {
            ButterKnife.bind(this, view);
            this.context = context;
        }

        boolean clickAble = true;


        @OnClick({R.id.et_suggest, R.id.img_recognize, R.id.recipients, R.id.copyto, R.id.exigency, R.id.ll_exigency, R.id.history, R.id.showstatus, R.id.status_stocks, R.id.status_inhand, R.id.status_untreade, R.id.ll_checkcontract, R.id.switch_wholeday, R.id.ll_wholeday, R.id.begin, R.id.finish, R.id.repeat, R.id.tag, R.id.invitee, R.id.ll_schedule, R.id.appointmentlawyer, R.id.appointmenttime, R.id.place, R.id.ll_appointmentlawyer, R.id.img_accessory})
        public void onViewClicked(View view) {
            if (!clickAble)
                return;
            switch (view.getId()) {
                case R.id.et_suggest:
                    break;
                case R.id.img_recognize:
                    IflyUtil iflyUtil = new IflyUtil();
                    iflyUtil.recognize(context, etSuggest);
                    break;
                case R.id.recipients:
                    break;
                case R.id.copyto:
                    break;
                case R.id.exigency:
                    clickExigency();
                    break;
                case R.id.ll_exigency:
                    clickExigency();
                    break;
                case R.id.history:
                    break;
                case R.id.showstatus:
                    break;
                case R.id.status_stocks:
                    break;
                case R.id.status_inhand:
                    break;
                case R.id.status_untreade:
                    break;
                case R.id.ll_checkcontract:
                    break;
                case R.id.switch_wholeday:
                    break;
                case R.id.ll_wholeday:
                    break;
                case R.id.begin:
                    break;
                case R.id.finish:
                    break;
                case R.id.repeat:
                    break;
                case R.id.tag:
                    break;
                case R.id.invitee:
                    break;
                case R.id.ll_schedule:
                    break;
                case R.id.appointmentlawyer:
                    break;
                case R.id.appointmenttime:
                    break;
                case R.id.place:
                    break;
                case R.id.ll_appointmentlawyer:
                    break;
                case R.id.img_accessory:
                    clickFile();
                    break;
            }
        }

        public void setClickAble(boolean clickAble) {
            this.clickAble = clickAble;
        }


        //紧急按钮
        private void clickExigency() {
            if (swichtEigency.isChecked()) {
                swichtEigency.setChecked(false);
            } else {
                swichtEigency.setChecked(true);
            }
        }

        private void clickFile() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//无类型限制
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            ((Activity) context).startActivityForResult(intent, 100);
        }
    }

}
